package cn.sinobest.octopus.rpc;

import org.apache.thrift.TException;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.server.TThreadPoolServer.Args;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.sinobest.knob.core.meta.WorkerMeta.State;
import cn.sinobest.knob.worker.Worker;

public class Monitor implements RoleHandle.Iface{
	
	private final Logger LOG = LoggerFactory.getLogger(getClass());
	
	private Worker worker;
	private int monitorPort;
	
	public Monitor(Worker worker, int monitorPort) {
		this.worker = worker;
		this.monitorPort = monitorPort;
	}
	
	public RtnMsg stopInstance(boolean immediately) throws TException {
		worker.exitInstance(immediately);
		return new RtnMsg(0, "ok");
	}

	public RtnMsg checkStatus() throws TException {
		State st = worker.getWorkerMeta().getState();
		return new RtnMsg(st.getValue(), st.name());
	}

	public boolean serve() throws Exception {
		RoleHandle.Processor<Monitor> processor = new RoleHandle.Processor<Monitor>(this);
		TServerTransport serverTransport = new TServerSocket(monitorPort);
		TServer server = new TSimpleServer(new Args(serverTransport).processor(processor));
		server.serve();
		return true;
	}
}
